//
//  CityInfoTableView.m
//  CityInfoChooseView
//
//  Created by 正合适 on 2017/10/12.
//  Copyright © 2017年 正合适. All rights reserved.
//

#import "CityInfoTableView.h"
#import "CityInfoListCell.h"

@interface CityInfoTableView ()
/**<#desc#>*/
@property (nonatomic, strong) NSMutableArray *datas;
@end

@implementation CityInfoTableView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        [self createUI];
    }
    return self;
}

#pragma mark - 初始化界面
- (void)createUI {
    _datas = [NSMutableArray array];
    self.dataSource = self;
    self.delegate = self;
    self.rowHeight = [CityInfoListCell cellHeight];
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark - 配置数据
- (void)configData:(NSArray<CityInfoModel *> *)datas {
    _datas = datas.mutableCopy;
    [self reloadData];
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakself configScrollToSelectedRow];
    });
}

#pragma mark - 让被选择的row可见
- (void)configScrollToSelectedRow {
    NSInteger index = -1;
    for (NSInteger i = 0; i < _datas.count; i ++) {
        CityInfoModel *model = _datas[i];
        if (model.isSelected) {
            index = i;
            break;
        }
    }
    if (index !=-1 && _datas.count > 0) {
        NSArray *visibleIndexPaths = [self indexPathsForVisibleRows];
        BOOL isVisible = NO;
        for (NSIndexPath *path in visibleIndexPaths) {
            if (path.row == index) {
                isVisible = YES;
                break;
            }
        }
        if (!isVisible) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [self scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CityInfoListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[CityInfoListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    CityInfoModel *model = _datas[indexPath.row];
    [cell configTitle:model.areaName isSelected:model.isSelected];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.tableViewCellCilckBlock) {
        self.tableViewCellCilckBlock(tableView.tag,indexPath.row);
    }
}

@end
